#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define ERROR NULL

typedef struct LNode *PtrToLNode;
struct LNode {
    double Data;
    PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;

int Length(List L);
List Insert(List L, double X, int i);
bool Delete(List L, int i);

int main()
{
    List example_list = NULL;
    double number;
    int insert_position = 1, delete_position = 0;

    for (;;)
    {
        printf("Enter the number to input(0 to finish) : ");
        scanf("%lf", &number);
        if (number == 0)
            break;
        example_list = Insert(example_list, number, insert_position++);
    }

    printf("\nThe list have %d numbers : \n", Length(example_list));
    for (Position p = example_list; p != NULL; p = p->Next)
        printf("%lf  ", p->Data);
    printf("\n\n");

    for (;;)
    {
        printf("Enter the number position to delete(0 to finish) : ");
        scanf("%d", &delete_position);
        if (delete_position == 0)
            break;
        if (Delete(example_list, delete_position - 1))
            printf("Delete Success !\n");
    }

    printf("\nThe list have %d numbers : \n", Length(example_list));
    for (Position p = example_list; p != NULL; p = p->Next)
        printf("%lf  ", p->Data);

    return 0;
}

int Length(List L)
{
    Position p;
    int cnt = 0;
    p = L;
    while (p)
    {
        p = p->Next;
        cnt++;
    }

    return cnt;
}

List Insert(List L, double X, int i)
{
    Position tmp, pre;

    tmp = (Position)malloc(sizeof(struct LNode));
    tmp->Data = X;
    
    if (i == 1)
    {
        tmp->Next = L;
        printf("Initial list success !\n");
        return tmp;
    }
    else
    {
        int cnt = 1;
        pre = L;
        while (pre && cnt < i - 1)
        {
            pre = pre->Next;
            cnt++;
        }
        
        if (pre == NULL || cnt != i - 1)
        {
            /*
            printf("cnt = %d\n", cnt);
            if (pre == NULL)
                printf("pre is NULL !\n");
            */
            printf("Invaild Insert Position !\n");
            free(tmp);
            return ERROR;
        }
        else
        {
            tmp->Next = pre->Next;
            pre->Next = tmp;
            printf("Insert Success !\n");
            return L;
        }
    }
}

bool Delete(List L, int i)
{
    Position tmp, pre;
    int cnt = 0;

    pre = L;
    while (pre && cnt < i - 1)
    {
        pre = pre->Next;
        cnt++;
    }
    if (pre == NULL || cnt != i - 1 || pre->Next == NULL)
    {
        printf("Invalid Delete Position !\n");
        return false;
    }
    else
    {
        tmp = pre->Next;
        pre->Next = tmp->Next;
        free(tmp);
        return true;
    }
}